<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>06-绘制物体的三要素之材质</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body {
      width: 100%;
      height: 100%;
    }
  </style>
</head>

<body>
  <script type="module">
    import * as THREE from "three";
    import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
    // 创建场景
    const scene = new THREE.Scene();
    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      1,
      1000
    );
    camera.position.set(0, 10, 20);
    camera.lookAt(0, 0, 0);
    // 创建渲染器 
    const renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    // 设置渲染器大小
    renderer.setSize(window.innerWidth, window.innerHeight);
    // 把渲染的canvas内容添加到body
    document.body.appendChild(renderer.domElement);

    // 环境光 柔和的白光
    const ambientLight = new THREE.AmbientLight(0x404040);
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    directionalLight.position.set(3, 3, 3);
    scene.add(ambientLight, directionalLight);
    // 创建结构 几何体
    const geometry = new THREE.SphereGeometry(2, 32, 32);
    const loader = new THREE.TextureLoader();
    // const texture = loader.load("../images/01.jpg");
    // 创建材质 外观
    const material = new THREE.MeshStandardMaterial({
      color: 0xff000,
      roughness: 0.5,
      metalness: 1
      // emissive: 0xff00000,
      // map: texture
    });
    // 结构和材质组合，生成一个物体
    const cube = new THREE.Mesh(geometry, material);
    // 将物体添加到场景中
    scene.add(cube);

    // 创建轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);

    // 开启物体的阻尼动画效果
    controls.enableDamping = true;

    // 监听controls的change事件
    controls.addEventListener("change", () => {
      // 交互的鼠标每次发生变化，都需要渲染一次(如果用了animate函数就不需要).
      renderer.render(scene, camera);
    });
    renderer.render(scene, camera);


    function animate() {
      // renderer.render(scene, camera);
      // 计算每一帧的运动惯性和减速的量，实现阻尼效果
      controls.update();
      requestAnimationFrame(animate);
    } 

    // 添加动画并渲染
    animate();

    // 监听屏幕变化
    window.addEventListener("resize", function () {
      // 更新摄像头
      camera.aspect = window.innerWidth / window.innerHeight;
      // 更新摄像机的投影矩阵
      camera.updateProjectionMatrix();
      // 更新渲染器
      renderer.setSize(window.innerWidth, window.innerHeight);
      // 设置渲染器的像素比
      renderer.setPixelRatio(window.devicePixelRatio);
    });
  </script>
</body>

</html>